package com.xzt.meeting.controller;


import com.alibaba.fastjson.JSON;
import com.xzt.meeting.entity.User;
import com.xzt.meeting.utils.MeetingHashMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Map;

/**
 * @Author xzt
 * @Date 2022/5/6 8:33
 * @Version 1.0
 * @Introduce
 */
public class BaseServlet extends HttpServlet {

    // 当前会话session
    public HttpSession session;

    // 当前登录的用户
    public User loginUser = null;

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        session = req.getSession();


        loginUser = (User) session.getAttribute("loginUser");


        req.setCharacterEncoding("utf-8");

        String uri = req.getRequestURI();

        uri = uri.substring(uri.lastIndexOf("/") + 1);

        Class targetClass = this.getClass();

        try {

            Method method = targetClass.getMethod(uri, HttpServletRequest.class, HttpServletResponse.class);

            method.invoke(this, req, resp);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static Map<String, String> getParam(HttpServletRequest request) {

        Map<String, String> returnMap = new MeetingHashMap();


        Map<String,String[]> parameterMap = request.getParameterMap();

        for (String key : parameterMap.keySet()) {

            String[] values = parameterMap.get(key);
            if (values.length > 1) {


                String val = Arrays.toString(values);

                returnMap.put(key, val);
            } else {
                //只要第0个下标的值
                returnMap.put(key, values[0]);
            }
        }

        return returnMap;
    }

    public void writerObjToString(HttpServletResponse response, Object obj) {
        try {

            String jsonStr = JSON.toJSONString(obj);

            // 统一设置编码
            response.setContentType("application/json;charset=utf8");
            response.getWriter().write(jsonStr);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
